package com.neusoft.admin.controller;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Map;

import com.neusoft.admin.method.Show;
import com.neusoft.admin.method.iniRead;
import com.neusoft.grid.entity.Mission;
import com.neusoft.neps.entity.user;

import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TreeCell;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;

public class adminViewControl {
    @FXML
    private Button btn_exit;
    @FXML
    private TreeView<String> treeView;
    @FXML
    private StackPane stackPane;
    @FXML
    private ImageView imageView;
    @FXML
    private Label usernameLabel;
    @FXML
    private HBox hbox;
    @FXML
    private ImageView image;
    private String userName;

    public adminViewControl() {
    }

    public adminViewControl(String userName) {
        this.userName = userName;
    }

    @FXML
    public void initialize() throws IOException {
        try {
            File file = new File("src/com/neusoft/admin/data/missions.txt");
            if (!file.exists()) {
                if (file.createNewFile()) {
                    System.out.println("文件不存在，已创建");
                } else {
                    System.out.println("文件创建失败");
                }
            }
            List<Mission> newmissions = iniRead.readMissions("src/com/neusoft/neps/data/missions.txt");
            System.out.println("新文件读取成功");
            // 读取旧任务列表
            List<Mission> oldmissions = iniRead.readMissions("src/com/neusoft/admin/data/missions.txt");
            System.out.println("旧文件读取成功");
            // 读取新任务列表
            for (Mission newMission : newmissions) {
                boolean isExist = false;
                // 检查新任务的 Number 是否已存在于旧任务列表中
                for (Mission oldMission : oldmissions) {
                    if (newMission.getNumber().equals(oldMission.getNumber())) {
                        isExist = true;
                        System.out.println("任务已存在，任务编号: " + newMission.getNumber());
                        break;
                    }
                }
                // 若任务不存在，则添加到旧任务列表
                if (!isExist) {
                    oldmissions.add(newMission);
                    iniRead.writeMission("src/com/neusoft/admin/data/mission.txt", newmissions);
                    System.out.println("任务不存在，添加新任务，任务编号: " + newMission.getNumber());
                }
            }
            // 将更新后的任务列表写回文件
            iniRead.writeListMissions("src/com/neusoft/admin/data/missions.txt", oldmissions);
            Map<String, user> userMap = iniRead.readUsers("src/com/neusoft/neps/data/users.txt");
            iniRead.writeUsers("src/com/neusoft/admin/data/users.txt", userMap);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("读取任务列表失败");
        }

        System.out.println("初始化");
        image.setImage(new ImageView("com/neusoft/admin/data/2.jpg").getImage());
        usernameLabel.setText(userName);
        HBox.setHgrow(hbox, Priority.ALWAYS);
        TreeItem<String> rootItem = new TreeItem<>("Root");
        rootItem.setExpanded(true);
        TreeItem<String> child1 = new TreeItem<>("公众监督数据管理");
        TreeItem<String> child2 = new TreeItem<>("统计数据管理");
        TreeItem<String> grandChild11 = new TreeItem<>("公众监督数据列表");
        TreeItem<String> grandChild12 = new TreeItem<>("确认AQI数据列表");
        TreeItem<String> grandChild21 = new TreeItem<>("省分组检查统计");
        TreeItem<String> grandChild22 = new TreeItem<>("AQI指数分布统计");
        TreeItem<String> grandChild23 = new TreeItem<>("AQI指数趋势统计");
        TreeItem<String> grandChild24 = new TreeItem<>("其它数据统计");
        child1.getChildren().addAll(grandChild11, grandChild12);
        child2.getChildren().addAll(grandChild21, grandChild22, grandChild23, grandChild24);
        rootItem.getChildren().addAll(child1, child2);
        treeView.setRoot(rootItem);
        treeView.setShowRoot(false);
        expandAll(rootItem);

        treeView.styleProperty().set("-fx-font-size: 14px; -fx-background-color: #79BBFF;-fx-padding: 10px 0; ");
        treeView.setCellFactory(new Callback<TreeView<String>, TreeCell<String>>() {
            @Override
            public TreeCell<String> call(TreeView<String> param) {
                return new TreeCell<String>() {
                    @Override
                    protected void updateItem(String item, boolean empty) {
                        super.updateItem(item, empty);
                        if (empty || item == null) {
                            setText(null);
                        } else {
                            setText(item);
                        }
                        setStyle("-fx-padding: 10px 0; -fx-background-color: transparent;");
                    }
                };
            }
        });
        treeView.getSelectionModel().selectedItemProperty().addListener((_, oldValue, newValue) -> {
            if (newValue != null) {
                handleNodeSelection(newValue);
            }
        });

    }

    /**
     * @param selectedItem 被选中的节点
     */
    private void handleNodeSelection(TreeItem<String> selectedItem) {
        String nodeValue = selectedItem.getValue();
        System.out.println("选中的节点: " + nodeValue);
        // 根据不同的节点值执行不同的操作
        switch (nodeValue) {
            case "公众监督数据列表":
                queryFeedbackList();
                break;
            case "确认AQI数据列表":
                queryAQIconfirmList();
                break;
            case "省分组检查统计":
                queryProvince();
                break;
            case "AQI指数分布统计":
                querydistributetotalstatis();
                break;
            case "AQI指数趋势统计":
                querytrendtotalstatis();
                break;
            case "其它数据统计":
                queryOther();
                break;
            case "公众监督数据管理", "统计数据管理":
                closeStackPane();
                break;
            default:
                break;
        }
    }

    private void expandAll(TreeItem<String> item) {
        if (item != null && !item.isLeaf()) {
            item.setExpanded(true);
            for (TreeItem<String> child : item.getChildren()) {
                expandAll(child);
            }
        }
    }

    public void queryProvince() {
        try {
            Show.viewShow(stackPane, getClass().getResource("/com/neusoft/admin/view/provinceView.fxml"));
            System.out.println("查询成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void queryFeedbackList() {
        try {
            URL url = getClass().getResource("/com/neusoft/admin/view/feedbackListView.fxml");
            Show.viewShow(stackPane, url);
            System.out.println("反馈查询成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void queryAQIconfirmList() {
        try {
            Show.viewShow(stackPane, getClass().getResource("/com/neusoft/admin/view/AQIconfirmListView.fxml"));
            System.out.println("AQI确认查询成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void queryOther() {
        try {
            Show.viewShow(stackPane, getClass().getResource("/com/neusoft/admin/view/otherView.fxml"));
            System.out.println("其他查询成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void querydistributetotalstatis() {
        try {
            Show.viewShow(stackPane, getClass().getResource("/com/neusoft/admin/view/AQIdistributetotalstatis.fxml"));
            System.out.println("AQI统计查询成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void querytrendtotalstatis() {
        try {
            Show.viewShow(stackPane, getClass().getResource("/com/neusoft/admin/view/AQItrendtotalstatis.fxml"));
            System.out.println("AQI趋势查询成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void closeStackPane() {
        stackPane.getChildren().clear();
        ImageView imageView = new ImageView("com/neusoft/admin/data/2.jpg");
        imageView.fitWidthProperty().bind(stackPane.widthProperty());
        imageView.fitHeightProperty().bind(stackPane.heightProperty());
        imageView.setPreserveRatio(true);
        imageView.setSmooth(true);
        imageView.setCache(true);
        stackPane.getChildren().add(imageView);
    }

    public void exit() {
        try {
            Stage stage = (Stage) btn_exit.getScene().getWindow();
            URL url = getClass().getResource("/com/neusoft/admin/view/IndexView.fxml");
            Show.show(stage, url, "登录页面");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
